//
//  LLTagView.m
//  标签
//
//  Created by admin on 2018/12/10.
//  Copyright © 2018 LG. All rights reserved.
//

#import "LLTagView.h"
#import "LLTagModel.h"
#import "LLTagViewCell.h"
#import "LLHorizontalEqulHeightFlowLayout.h"

static NSString *cellIdentifier = @"lltagviewcellidentifier";

@interface LLTagView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
{
//    UICollectionViewFlowLayout *layout;
    
}

@property (nonatomic, strong) LLHorizontalEqulHeightFlowLayout *layout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *selectArray;  // 选好的
@property (nonatomic, copy) void(^selectItems)(NSArray *);
/// 将要选中的indexPath
@property (nonatomic, strong) NSIndexPath *shouldSelectIndexPath;

@end

@implementation LLTagView

- (instancetype)initWithFrame:(CGRect)frame dataArray:(nonnull NSArray *)dataArray selectItems:(nonnull void (^)(NSArray * _Nonnull))selectItems
{
    return [self initWithFrame:frame dataArray:dataArray selectItems:selectItems config:nil];
}

- (instancetype)initWithFrame:(CGRect)frame dataArray:(NSArray *)dataArray selectItems:(void (^)(NSArray * _Nonnull))selectItems config:(LLTagConfig *)config
{
    self = [super initWithFrame:frame];
    if (self) {
        
        if (config) {
            self.config = config;
        }
        self.selectItems = selectItems;
        [self setupDataWithArray:dataArray];
        [self.collectionView reloadData];
        [self reloadFrame];     // 改变高度
        
    }
    return self;
}

- (void)resetView
{
    [self.selectArray removeAllObjects];
    [self.collectionView reloadData];
    if (self.selectItems) {
        self.selectItems(self.selectArray);
    }
}

- (void)setupDatasArray:(NSArray *)dataArray
{
    [self setupDataWithArray:dataArray];
    [self.collectionView reloadData];
    [self reloadFrame];     // 改变高度
}

- (void)setDefaultSelectIndex:(NSInteger)index
{
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    
    LLTagModel *model = self.dataArray[index];
    
    if (!self.allowMutiSelect) {
        [self.selectArray removeAllObjects];
        [self.selectArray addObject:model.title];
    } else {
        if (![self.selectArray containsObject:model.title]) {
            [self.selectArray addObject:model.title];
        }
    }
    
    if (self.selectItems) {
        self.selectItems(self.selectArray);
    }
}

- (void)setDefaultSelectIndexs:(NSArray<NSNumber *> *)indexs
{
    for (NSNumber *num in indexs) {
        [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:num.integerValue inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
        LLTagModel *model = self.dataArray[num.integerValue];
        
        if (!self.allowMutiSelect) {
            [self.selectArray removeAllObjects];
            [self.selectArray addObject:model.title];
        } else {
            if (![self.selectArray containsObject:model.title]) {
                [self.selectArray addObject:model.title];
            }
        }
    }
    if (self.selectItems) {
        self.selectItems(self.selectArray);
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LLTagModel *model = self.dataArray[indexPath.row];
    LLTagViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.config = self.config;
    cell.model = model;
    return cell;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.shouldSelectIndexPath = indexPath;
    
    if (!self.canCancelSelect) {
        return YES;
    }
    LLTagViewCell *cell = (LLTagViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (cell.selected) {
        // 单选取消选中
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        [self collectionView:collectionView didDeselectItemAtIndexPath:indexPath];
        return NO;
    }
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    LLTagModel *model = self.dataArray[indexPath.row];
    
    if (!self.allowMutiSelect) {
        [self.selectArray removeAllObjects];
        [self.selectArray addObject:model.title];
    } else {
        if (![self.selectArray containsObject:model.title]) {
            [self.selectArray addObject:model.title];
        }
    }
    
    if (self.selectItems) {
        self.selectItems(self.selectArray);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    LLTagModel *model = self.dataArray[indexPath.row];
    [self.selectArray removeObject:model.title];
    
    if (!self.allowMutiSelect) {
        if (self.canCancelSelect && self.shouldSelectIndexPath == indexPath) {
            if (self.selectItems) {
                self.selectItems(self.selectArray);
            }
        }
    } else {
        if (self.selectItems) {
            self.selectItems(self.selectArray);
        }
    }
    
    
    
}

- (void)setupDataWithArray:(NSArray *)array
{
    [self.dataArray removeAllObjects];
    CGFloat fontSize = 0;
    if (self.config) {
        fontSize = self.config.fontSize;
    }
    for (NSString *title in array) {
        LLTagModel *model = [LLTagModel setTagWithTitle:title fontSize:fontSize];
        [self.dataArray addObject:model];
    }
    
}

- (void)setConfig:(LLTagConfig *)config
{
    _config = config;
    self.layout.lineSpace = config.minLineSpace == 0 ? 5 : config.minLineSpace;
    self.layout.itemSpace = config.minItemSpace == 0 ? 5 : config.minItemSpace;
    self.layout.itemHeight = config.itemHeight == 0 ? 30 : config.itemHeight;
    if (config.sectionInset.top == 0 && config.sectionInset.left == 0 && config.sectionInset.bottom == 0 && config.sectionInset.right == 0) {
    } else {
        self.layout.sectionInsets = config.sectionInset;
    }
    [self.collectionView reloadData];
    [self reloadFrame];     // 改变高度
}

- (void)reloadFrame
{
    [self layoutIfNeeded];
    
    CGRect rect = self.frame;
    rect.size.height = self.collectionView.contentSize.height;
    self.frame = rect;
    self.collectionView.frame = self.bounds;
    
    // collectionView 加载完执行，因为 collectionView 加载是在主队列中进行的，所以改变frame也放到主队列才行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        NSLog(@"高度 == %@", NSStringFromCGSize(self.collectionView.contentSize));
        CGRect rect = self.frame;
        rect.size.height = self.collectionView.contentSize.height;
        self.frame = rect;
        self.collectionView.frame = self.bounds;
        
        if (self.needReloadView) {
            [self.needReloadView setNeedsLayout];
        }
    });
}

- (void)setAllowMutiSelect:(BOOL)allowMutiSelect
{
    _allowMutiSelect = allowMutiSelect;
    if (allowMutiSelect) {
        _canCancelSelect = YES;
    }
    self.collectionView.allowsMultipleSelection = allowMutiSelect;
}

- (void)setCanCancelSelect:(BOOL)canCancelSelect
{
    if (self.allowMutiSelect) {
        _canCancelSelect = YES;
        return;
    }
    _canCancelSelect = canCancelSelect;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:backgroundColor];
    self.collectionView.backgroundColor = backgroundColor;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[LLTagViewCell class] forCellWithReuseIdentifier:cellIdentifier];
        [self addSubview:_collectionView];
        
    }
    return _collectionView;
}

- (LLHorizontalEqulHeightFlowLayout *)layout
{
    if (!_layout) {
        _layout = [[LLHorizontalEqulHeightFlowLayout alloc] init];
        _layout.lineSpace = 5;  // 行间距
        _layout.itemSpace = 5; // item 间距
        _layout.itemHeight = 30; // item 高度
        _layout.sectionInsets = UIEdgeInsetsMake(5, 10, 5, 10);
        _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        __weak typeof(self) weakSelf = self;
        [self.layout configItemWidth:^CGFloat(NSIndexPath * _Nonnull indexPath, CGFloat height) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            //如果配置了宽度，直接返回固定的宽度
            if (strongSelf.config.itemWidth > 0) {
                return strongSelf.config.itemWidth;
            }
            
            CGFloat minWidth = strongSelf.config.itemMinWidth;
            LLTagModel *model = strongSelf.dataArray[indexPath.row];
            return (model.width + 10 < minWidth) ? minWidth : model.width + 10;
            
        }];
        
    }
    return _layout;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)selectArray
{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

@end
